<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生高亮查询" prop="name">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入医生信息"
          clearable
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker clearable
                        v-model="queryParams.birthDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="居住地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入居住地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生执业证书编号" prop="licenseNumber">
        <el-input
          v-model="queryParams.licenseNumber"
          placeholder="请输入医生执业证书编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执业证书发放日期" prop="licenseissueDate">
        <el-date-picker clearable
                        v-model="queryParams.licenseissueDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择执业证书发放日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="执业证书到期日期" prop="licenseExpireDate">
        <el-date-picker clearable
                        v-model="queryParams.licenseExpireDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择执业证书到期日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="图片" prop="profilePic">
        <el-input
          v-model="queryParams.profilePic"
          placeholder="请输入图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['doctor:doctor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['doctor:doctor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['doctor:doctor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['doctor:doctor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="医生姓名" align="center" prop="name" />
      <el-table-column label="医生性别" align="center" prop="sex" />
      <el-table-column label="出生日期" align="center" prop="birthDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="居住地址" align="center" prop="address" />
      <el-table-column label="医生执业证书编号" align="center" prop="licenseNumber" />
      <el-table-column label="执业证书发放日期" align="center" prop="licenseissueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.licenseissueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执业证书到期日期" align="center" prop="licenseExpireDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.licenseExpireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属医院" align="center" prop="hospitalName" />
      <el-table-column label="医院等级" align="center" prop="hospitalLevel" >
        <template slot-scope="scope">
          <span v-if="scope.row.hospitalLevel==0">三甲</span>
          <span v-if="scope.row.hospitalLevel==1">二甲</span>
          <span v-if="scope.row.hospitalLevel==2">一甲</span>
        </template>
      </el-table-column>


      <el-table-column label="所属科室" align="center" prop="departmentsName" />
      <el-table-column label="个人简介" align="center" prop="bio" />
      <!--      <el-table-column label="图片" align="center" prop="profilePic" />-->
      <el-table-column label="医生图片" align="center" prop="profilePic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.profilePic" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态" align="center" prop="status" v-if="status==1"></el-table-column>>-->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            inactive-value="2"
            active-value="1"
            @change="updateAdvertiseStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['doctor:doctor:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['doctor:doctor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改医生微服务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-steps :active="active" finish-status="success">
          <el-step title="医生基本信息"></el-step>
          <el-step title="医生上班信息"></el-step>
          <el-step title="标签信息"></el-step>
        </el-steps>
        <div v-show="active==1">
          <el-form-item label="医生姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入医生姓名" />
          </el-form-item>
          <el-form-item label="医生性别" prop="name">
            <el-input v-model="form.sex" placeholder="请输入性别" />
          </el-form-item>
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker clearable
                            v-model="form.birthDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择出生日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="居住地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入居住地址" />
          </el-form-item>
          <el-form-item label="医生执业证书编号" prop="licenseNumber">
            <el-input v-model="form.licenseNumber" placeholder="请输入医生执业证书编号" />
          </el-form-item>
          <el-form-item label="执业证书发放日期" prop="licenseissueDate">
            <el-date-picker clearable
                            v-model="form.licenseissueDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择执业证书发放日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="执业证书到期日期" prop="licenseExpireDate">
            <el-date-picker clearable
                            v-model="form.licenseExpireDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择执业证书到期日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input v-model="form.bio" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="医生图片" :label-width="formLabelWidth">
            <el-upload action="/dev-api/doctor/doctor/upload"
                       list-type="picture-card"
                       :fileList="fileList"
                       :on-preview="handlePictureCardPreview"
                       :on-success="handleAvatarSuccess"
                       :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </div>

        <div v-show="active==2" style="width: 300px;height: 400px">
          <span class="demonstration">选择所属医院信息</span>
          <el-cascader
            v-model="selectedOptions"
            :options="formattedOptions"
            :props="{ checkStrictly: true }"
            placeholder="请选择"
            @change="handleChange"
            style="width: 350px;height: 350px"
          ></el-cascader>
        </div>
        <div v-show="active==3" style="width: 200px;height: 200px">

          <el-tag
            :key="tag"
            v-for="tag in tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag.labelName}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </div>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="pre" v-show="active>1">上一步</el-button>
        <el-button style="margin-top: 12px;" @click="next" v-show="active<3">下一步</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDoctor,
  getDoctor,
  delDoctor,
  addDoctor,
  updateDoctor,
  updateStatus,
  listLabel,
  addLabel, delLabel, selectHospital, selectDepart
} from "@/api/doctor/doctor";

export default {
  name: "Doctor",
  data() {
    return {
      idList:[],
      selectedOptions:[],
      hospital:[],
      tags: [],
      inputVisible: false,
      inputValue: '',

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生微服务表格数据
      doctorList: [],
      // 弹出层标题
      title: "",
      active:1,
      stepCn:{
        1:'医生基本信息',
        2:'商品规格信息',
        3:'商品描述信息'
      },
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        keyWord: null,
        sex: null,
        birthDate: null,
        phone: null,
        address: null,
        licenseNumber: null,
        licenseissueDate: null,
        licenseExpireDate: null,
        hospitalId: null,
        departmentId: null,
        bio: null,
        profilePic: null,
        status: null
      },
      // 表单参数
      form: {
        ids:[]
      },
      dialogVisible:false,
      dialogImageUrl:'',
      fileList:[],
      doctor:{},
      label:{
        labelName:""
      },
      formattedOptions: [], // 用于存储转换后的数据

      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getLabelList();
    // this.getHospital();
    this.getDepart();

  },
  methods: {
    //医院列表
    // getHospital(){
    //   selectHospital().then(res=>{
    //     this.hospital=res.data
    //   })
    // },
    getDepart(){
      selectDepart().then(res=>{
        res.data.forEach(hospital => {
          const hospitalOption = {
            value: hospital.hospitalId,
            label: hospital.hospitalName,
            children: hospital.departmentsVos.map(department => {
              return {
                value: department.departmentsId,
                label: department.departmentsName,
                children: department.childrenList.map(subDepartment => {
                  // 注意：这里我们假设子科室下不再有更深的层级，而是直接展示医生列表
                  // 如果你的数据结构不同，需要相应调整
                  return {
                    value: subDepartment.departmentsId, // 这里可能需要调整，因为通常医生列表不会作为级联选择器的层级
                    label: subDepartment.departmentsName,
                    // 如果需要在级联选择器中展示医生，这里需要特殊处理，但通常不推荐这样做
                    // 因为级联选择器不适合展示过多层级或大量数据
                    // 下面的代码仅作为示例，实际上你可能需要设计一个不同的UI来展示医生列表
                    // children: subDepartment.madicalDoctorList.map(doctor => ({
                    //   value: doctor.id,
                    //   label: doctor.name
                    // }))
                  };
                })
              };
            })
          };
          this.formattedOptions.push(hospitalOption);
        });
      })
    },
    handleChange(value) {
      // 处理级联选择器值变化时的逻辑
      this.form.hospitalId = value[0]
      this.form.departmentId = value[1]
      // 根据选中的值（医院ID和科室ID），你可以进一步获取并展示对应的医生列表
    },

    //标签列表
    getLabelList(){
      listLabel().then(res=>{
        this.tags=res.data
      })
    },
    // xz(labelId){
    //   alert(labelId)
    // },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      this.label.labelName = inputValue
      addLabel(this.label).then(
        res=>{
          if (inputValue) {
            this.tags.push(inputValue);
            this.getLabelList()
          }
          this.inputVisible = false;
          this.inputValue = '';
        }
      )
    },
    handleClose(tag) {
      delLabel(tag.labelId).then(res=>{
        this.getLabelList()
      })
    },




    //上一步，下一步
    pre() {
      this.active--;
      this.swtichStepCn();
    },
    next() {
      this.active++;
      this.swtichStepCn();
    },


    //上传图片
    handleAvatarSuccess(response){
      alert(response)
      this.form.profilePic=response
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //修改状态
    updateAdvertiseStatus(row){
      this.$nextTick(() => {
        // 在这里执行任何需要等待 DOM 更新的操作
        if (row.status==1){
          this.doctor.id=row.id,
            this.doctor.status=2
          updateStatus(this.doctor).then(response=>{
            if (response.code===200){
              this.$message.success(response.data);
            }else {
              this.$message.error(response.mgs);
            }
          })
        }
        if (row.status==2){
          this.doctor.id=row.id,
            this.doctor.status=1
          updateStatus(this.doctor).then(response=>{
            if (response.code===200){
              this.$message.success(response.data);
            }else {
              this.$message.error(response.mgs);
            }
          })
        }
        // 其他逻辑...
      });
    },


    /** 查询医生微服务列表 */
    getList() {
      this.loading = true;
      listDoctor(this.queryParams).then(response => {
        this.doctorList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sex: null,
        birthDate: null,
        phone: null,
        address: null,
        licenseNumber: null,
        licenseissueDate: null,
        licenseExpireDate: null,
        hospitalId: null,
        departmentId: null,
        bio: null,
        profilePic: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuerys() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加医生微服务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDoctor(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改医生微服务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDoctor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.tags.forEach(da =>{
              this.idList.push(da.labelId)
            })
            this.form.ids = this.idList
            alert(this.form.ids)
            addDoctor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除医生微服务编号为"' + ids + '"的数据项？').then(function() {
        return delDoctor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('doctor/doctor/export', {
        ...this.queryParams
      }, `doctor_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

